package collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * Created with IntelliJ IDEA
 * Description:Iterator的学习(Collection继承它的接口)
 * User:22954
 * Date:2024-02-02
 * Time:1:11
 */
@SuppressWarnings("all")
public class Iterator_ {
    @SuppressWarnings("all")
    public static void main(String[] args) {
        ArrayList<Book> books = new ArrayList<>();
        books.add(new Book("Harry Potter",98));
        books.add(new Book("Mocking Bird",62));
        books.add(new Book("Black Tower",73));

        /*
          ArrayList继承Collection接口，Collection继承Iterator接口
          Iterator是迭代器
          迭代器类似指针，只能往后走不能往前走
         */
        Iterator<Book> iterator= books.iterator();
        /*
          iterator的while迭代快捷键 => itit
         */
        while (iterator.hasNext()) {
            System.out.println(iterator.next());//Book{name='Harry Potter', price=98} Book{name='Mocking Bird', price=62}Book{name='Black Tower', price=73}
        }
        /*
          要重置迭代器，重新生成新的迭代器指针
         */
        iterator= books.iterator();
        System.out.println(iterator.next());//Book{name='Harry Potter', price=98}
        /*
          增强for在编译list类时会转化为迭代器
          在编译普通数组时还是fori循环
          list的增强for迭代快捷键 =>iter
         */
        for (Object i: books){
            System.out.println(i);
        }//Book{name='Harry Potter', price=98} Book{name='Mocking Bird', price=62}Book{name='Black Tower', price=73}

    }
    public static void main1(String[] args) {
        Collection<Book> books = new ArrayList<>();
        books.add(new Book("Harry Potter",98));
        books.add(new Book("Mocking Bird",62));
        books.add(new Book("Black Tower",73));

        Iterator<Book> iterator= books.iterator();

    }
}
@SuppressWarnings("all")
class Book{
    String name;
    int price;

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Book(String name, int price) {
        this.name = name;
        this.price = price;
    }
}
